package com.vote.www.controller;



import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import javax.annotation.Resource;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.math.NumberUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.vote.www.core.page.Pagination;
import com.vote.www.domain.Czjvoteorder;
import com.vote.www.domain.vo.TUser;
import com.vote.www.domain.vo.VoteOreder;
import com.vote.www.service.CzjvoteorderService;



@Controller
public class CzjvoteorderController /*extends BaseController*/{
	private static final Logger log = LoggerFactory.getLogger(CzjvoteorderController.class);
	public CzjvoteorderController() {
	}
 
 
 	/**
	 * czj_voteorder  车主节排序新增页面
	 * 
	 * @param request
	 * @param model
	 * @return
	 */
	@RequestMapping("czjvoteorderAdd.do")
	public String add(HttpServletRequest request, ModelMap model) {
		model.addAttribute("czjvoteorder", new Czjvoteorder());
      setDict(model);
		return "czjvoteorderEdit";
	}

	/**
	 * czj_voteorder  车主节排序保存
	 * 
	 * @param czjvoteorder
	 * @param request
	 * @param model
	 * @return
	 */
	@RequestMapping("czjvoteorderSave.do")
	public String save(Czjvoteorder czjvoteorder, HttpServletRequest request,HttpServletResponse response, ModelMap model) throws Exception{

            String message =null;
		try {
			if(czjvoteorder.getVoteorderId()!=null&&!czjvoteorder.getVoteorderId().equals("")){
				// 编辑
				czjvoteorderService.updateCzjvoteorder(czjvoteorder);				
				if(czjvoteorder.getIsRelease()==1){	
					message = "1";
				}
				if(czjvoteorder.getIsRelease()==0){	
					message = "0";
				}	
				model.addAttribute("message",message);
				//tlogService.insertTloger(LoggerHelper.getTloger(request, LoggerHelper.OPERATING, "编辑czj_voteorder  车主节排序", "voteorderId="+czjvoteorder.getVoteorderId()));
			} else {
				// 新增
				//czjvoteorderService.insertCzjvoteorder(czjvoteorder);
				//tlogService.insertTloger(LoggerHelper.getTloger(request, LoggerHelper.OPERATING, "新增czj_voteorder  车主节排序", "voteorderId="+czjvoteorder.getVoteorderId()));
			}
   		} catch (Exception e) {
   			log.error("czjvoteorder save error:", e); 
            throw e;
   		}
      
		return "redirect:czjvoteorderEdit.do?voteorderId="+czjvoteorder.getVoteorderId();
	}
	
	/**
	 * czj_voteorder  车主节排序保存
	 * 
	 * @param czjvoteorder
	 * @param request
	 * @param model
	 * @return
	 */
	@RequestMapping("czjvoteorderSaveImg.do")
	public String save1(Czjvoteorder czjvoteorder,
			@RequestParam(value = "first", required = false)  MultipartFile first,
			@RequestParam(value = "second", required = false) MultipartFile second,
			@RequestParam(value = "third", required = false)  MultipartFile thrid,
			HttpServletRequest request,HttpServletResponse response, ModelMap model) throws Exception{
		

       
		try {
			if(czjvoteorder.getVoteorderId()!=null&&!czjvoteorder.getVoteorderId().equals("")){
				// 编辑
				//路径
				String pathRoot = request.getSession().getServletContext()
						.getRealPath("");
				String path = "";				
				// 第一张头像
				if (!first.isEmpty() && first.getSize()>0) {
					String uuid = UUID.randomUUID().toString().replaceAll("-", "");
					path = "/uploadvoteorder/" + uuid + "." + "jpg";
					File file = new File(pathRoot + "/uploadvoteorder");
					if (!file.exists()) {
						file.mkdir();
					}
					first.transferTo(new File(pathRoot + path));					
					//更新才删
					String jpgPic = czjvoteorder.getImgFirst();					
					if(jpgPic != null && jpgPic.length()>5){
						jpgPic = jpgPic.substring(1, jpgPic.length());
					}
					deleteFile(pathRoot + jpgPic);
					//更新才设置图片路径				
					czjvoteorder.setImgFirst(path);
				}
				
				// 第二张头像
				if (!second.isEmpty() && second.getSize()>0) {
					String uuid = UUID.randomUUID().toString().replaceAll("-", "");
					path = "/uploadvoteorder/" + uuid + "." + "jpg";
					File file = new File(pathRoot + "/uploadvoteorder");
					if (!file.exists()) {
						file.mkdir();
					}
					second.transferTo(new File(pathRoot + path));					
					//更新才删
					String jpgPic = czjvoteorder.getImgSecond();					
					if(jpgPic != null && jpgPic.length()>5){
						jpgPic = jpgPic.substring(1, jpgPic.length());
					}
					deleteFile(pathRoot + jpgPic);
					//更新才设置图片路径				
					czjvoteorder.setImgSecond(path);
				}				
				
				// 第三张头像
				if (!thrid.isEmpty() && thrid.getSize()>0) {
					String uuid = UUID.randomUUID().toString().replaceAll("-", "");
					path = "/uploadvoteorder/" + uuid + "." + "jpg";
					File file = new File(pathRoot + "/uploadvoteorder");
					if (!file.exists()) {
						file.mkdir();
					}
					thrid.transferTo(new File(pathRoot + path));					
					//更新才删
					String jpgPic = czjvoteorder.getImgThird();					
					if(jpgPic != null && jpgPic.length()>5){
						jpgPic = jpgPic.substring(1, jpgPic.length());
					}
					deleteFile(pathRoot + jpgPic);
					//更新才设置图片路径				
					czjvoteorder.setImgThird(path);
				}				
				
				
				czjvoteorderService.updateCzjvoteorder(czjvoteorder);										
				model.addAttribute("message",2);
				//tlogService.insertTloger(LoggerHelper.getTloger(request, LoggerHelper.OPERATING, "编辑czj_voteorder  车主节排序", "voteorderId="+czjvoteorder.getVoteorderId()));
			} else {
				// 新增
				//czjvoteorderService.insertCzjvoteorder(czjvoteorder);
				//tlogService.insertTloger(LoggerHelper.getTloger(request, LoggerHelper.OPERATING, "新增czj_voteorder  车主节排序", "voteorderId="+czjvoteorder.getVoteorderId()));
			}
   		} catch (Exception e) {
   			log.error("czjvoteorder save error:", e); 
            throw e;
   		}
      
		return "redirect:czjvoteorderEdit.do?voteorderId="+czjvoteorder.getVoteorderId();
	}	
	
	
	

	/**
	 * czj_voteorder  车主节排序删除
	 * 
	 * @param ids
	 * @return
	 */
	@RequestMapping("czjvoteorderDelete.do")
	public String delete(@RequestParam("ids") List<String> voteorderIdList) throws Exception{
		try {
         if (voteorderIdList != null) {
   			czjvoteorderService.deleteCzjvoteorder(voteorderIdList);
   		}
         } catch (Exception e) {
   			log.error("czjvoteorder delete error:", e); 
            throw e;
   		}
		return "redirect:czjvoteorderList.do";
	}
	 
	/**
	 * czj_voteorder  车主节排序编辑页面
	 * 
	 * @param voteorderId
	 * @param request
	 * @param model
	 * @return
	 */
	@RequestMapping("czjvoteorderEdit.do")
	public String edit(String voteorderId, HttpServletRequest request, ModelMap model) throws Exception{

      try {
   		Map<String, Object> param = new HashMap<String, Object>();
   		param.put("voteorderId", voteorderId);
         Czjvoteorder czjvoteorder = czjvoteorderService.getCzjvoteorder(param);
            
           
           String message = request.getParameter("message");                  
           request.setAttribute("message", message);

        
                 Map <String,Object> map = new HashMap<String, Object>();
                 map.put("yesterdayStr", czjvoteorder.getVoteDate());                              
   		model.addAttribute("czjvoteorder", czjvoteorder);
         model.addAttribute("actionEdit", request.getParameter("actionEdit"));
         setDict(model);
         } catch (Exception e) {
   			log.error("czjvoteorder edit error:", e); 
            throw e;
   		}
		return "czjvoteorderEdit";
	}

	/**
	 * czj_voteorder  车主节排序详情
	 * 
	 * @param voteorderId
	 * @param request
	 * @param model
	 * @return
	 */
	@RequestMapping("czjvoteorderDetail.do")
	public String detail(String voteorderId, HttpServletRequest request, HttpServletResponse response, ModelMap model) throws Exception{
      try {
      		Map<String, Object> param = new HashMap<String, Object>();
      		param.put("voteorderId", voteorderId);
            Czjvoteorder czjvoteorder = czjvoteorderService.getCzjvoteorder(param);
      		model.addAttribute("czjvoteorder", czjvoteorder);
            setDict(model);
            } catch (Exception e) {
   			log.error("czjvoteorder detail error:", e); 
            throw e;
   		  }
		return "czjvoteorderView";
	}
	 
	/**
	 * czj_voteorder  车主节排序查询（分页）
	 * 
	 * @param czjvoteorder
	 * @param pageNo
	 * @param request
	 * @param model
	 * @return
	 */
	@RequestMapping("czjvoteorderList.do")
	public String listPage(Czjvoteorder czjvoteorder, Integer pageNo, String order,
			String sort,HttpServletRequest request, ModelMap model) throws Exception{
		//获取昨天的投票数
		  Calendar   cal   =   Calendar.getInstance();
		  cal.add(Calendar.DATE,   -1);
		  String yesterday = new SimpleDateFormat( "yyyy-MM-dd ").format(cal.getTime());
		  System.out.println(yesterday);
          Map <String,Object> param = new HashMap<String, Object>();
          param.put("yesterdayStr", yesterday);        
         			
          Czjvoteorder czjvoteorderisNull = czjvoteorderService.getCzjvoteorderByvoteDate(param);          
	          //czjvoteorderisNull 为空插入数据库
	         if(czjvoteorderisNull==null){  
	        	 List<VoteOreder>  listOreder  =  czjvoteorderService.getVoteOreder(param);
	        	 if(listOreder.size()>0){          
		        //插入数据库  	                 
	                 Czjvoteorder czjvoteorder1 = new Czjvoteorder();//new新的czjvoteorder
		          if(listOreder.size()>0){		        	  
		        	  czjvoteorder1.setUserinfoIdFirst(listOreder.get(0).getUserinfoId());
		        	  czjvoteorder1.setExt1(listOreder.get(0).getNick());
		        	  czjvoteorder1.setExt4(listOreder.get(0).getPicPath());
		        	  czjvoteorder1.setNumFirst(listOreder.get(0).getNum());
		        	  czjvoteorder1.setRepresent1(listOreder.get(0).getRepresent());
		        	  if(listOreder.get(0).getPicPathPng()!=null){
		        		 czjvoteorder1.setImgFirst(listOreder.get(0).getPicPathPng());  
		        	  }else{
		        		  czjvoteorder1.setImgFirst(listOreder.get(0).getPicPath()); 
		        	  }		        	  
		          }
		          if(listOreder.size()>1){
		          czjvoteorder1.setUserinfoIdSecond(listOreder.get(1).getUserinfoId());
		          czjvoteorder1.setExt2(listOreder.get(1).getNick());
		          czjvoteorder1.setExt5(listOreder.get(1).getPicPath());
		          czjvoteorder1.setNumSecond(listOreder.get(1).getNum());
		          czjvoteorder1.setRepresent2(listOreder.get(1).getRepresent());
		        	  if(listOreder.get(1).getPicPathPng()!=null){
		        		 czjvoteorder1.setImgSecond(listOreder.get(1).getPicPathPng());  
		        	  }else{
		        		  czjvoteorder1.setImgSecond(listOreder.get(1).getPicPath()); 
		        	  }	
		          }
		          //判断有没有第二名
		          if(listOreder.size()==1){
		        	  request.setAttribute("message", "昨天,没第二名");
		          }
		          //判断有没有第三名
		          if(listOreder.size()==2){
		        	  request.setAttribute("message", "昨天,没第三名");
		          }
		          
		          if(listOreder.size()>2){
		          czjvoteorder1.setUserinfoIdThird(listOreder.get(2).getUserinfoId());
		          czjvoteorder1.setExt3(listOreder.get(2).getNick());
		          czjvoteorder1.setExt6(listOreder.get(2).getPicPath());
		          czjvoteorder1.setNumThird(listOreder.get(2).getNum());
		          czjvoteorder1.setRepresent3(listOreder.get(2).getRepresent());
		        	  if(listOreder.get(2).getPicPathPng()!=null){
		        		 czjvoteorder1.setImgThird(listOreder.get(2).getPicPathPng());  
		        	  }else{
		        		  czjvoteorder1.setImgThird(listOreder.get(2).getPicPath()); 
		        	  }	
		          }
		          if(listOreder.size()!=1 && listOreder.size()!=2){
			          czjvoteorder1.setIsRelease(1);
			          czjvoteorder1.setVoteDate(yesterday);
			          czjvoteorder1.setCreatetime(new Date());
			          czjvoteorderService.insertCzjvoteorder(czjvoteorder1);
		          } 
              }else{
           	   request.setAttribute("message", "昨天,没人投票");        	  
              }
          }
      try {   
   		if (pageNo == null)
   			pageNo = 1;
         Pagination pagination = czjvoteorderService.getCzjvoteorderList(toMap(czjvoteorder), 10, pageNo,
   				order, sort);                           
   		model.addAttribute("pagination", pagination);
         setDict(model);
         } catch (Exception e) {
			log.error("czjvoteorder listPage error:", e); 
         throw e;
		   }
		return "czjvoteorderList";
	}
	 
	/**
	 * czj_voteorder  车主节排序查询
	 * 
	 * @param czjvoteorder
	 * @param request
	 * @param model
	 * @return
	 */
	@RequestMapping("czjvoteorderList1.do")
	public String list(Czjvoteorder czjvoteorder, HttpServletRequest request, ModelMap model) throws Exception{
      try {
   		Map<String,Object> map = czjvoteorderService.getCzjvoteorderList(toMap(czjvoteorder));
   		model.addAttribute("list", map.get("rows"));
   		model.addAttribute("total", map.get("total"));
         setDict(model);
         } catch (Exception e) {
   			log.error("czjvoteorder list error:", e); 
            throw e;
   		}
		return "czjvoteorderList";
	}
	 

 	/***
	 * 将页面输入信息转成map
	 * 
	 * @param czjvoteorder
	 * @return
	 */	private Map<String,Object> toMap(Czjvoteorder czjvoteorder){
		Map<String,Object> map=new HashMap<String, Object>();
      		if(czjvoteorder.getVoteorderId()!=null&&!czjvoteorder.getVoteorderId().equals("")){
			map.put("voteorderId", czjvoteorder.getVoteorderId());
		}
		if(czjvoteorder.getUserinfoIdFirst()!=null&&!czjvoteorder.getUserinfoIdFirst().equals("")){
			map.put("userinfoIdFirst", czjvoteorder.getUserinfoIdFirst());
		}
		if(czjvoteorder.getUserinfoIdSecond()!=null&&!czjvoteorder.getUserinfoIdSecond().equals("")){
			map.put("userinfoIdSecond", czjvoteorder.getUserinfoIdSecond());
		}
		if(czjvoteorder.getUserinfoIdThird()!=null&&!czjvoteorder.getUserinfoIdThird().equals("")){
			map.put("userinfoIdThird", czjvoteorder.getUserinfoIdThird());
		}
		if(czjvoteorder.getImgFirst()!=null&&!czjvoteorder.getImgFirst().equals("")){
			map.put("imgFirst", czjvoteorder.getImgFirst());
		}
		if(czjvoteorder.getImgSecond()!=null&&!czjvoteorder.getImgSecond().equals("")){
			map.put("imgSecond", czjvoteorder.getImgSecond());
		}
		if(czjvoteorder.getImgThird()!=null&&!czjvoteorder.getImgThird().equals("")){
			map.put("imgThird", czjvoteorder.getImgThird());
		}
		if(czjvoteorder.getIsRelease()!=null&&!czjvoteorder.getIsRelease().equals("")){
			map.put("isRelease", czjvoteorder.getIsRelease());
		}
		if(czjvoteorder.getVoteDate()!=null&&!czjvoteorder.getVoteDate().equals("")){
			map.put("voteDate", czjvoteorder.getVoteDate());
		}
		if(czjvoteorder.getCreatetime()!=null&&!czjvoteorder.getCreatetime().equals("")){
			map.put("createtime", czjvoteorder.getCreatetime());
		}
		if(czjvoteorder.getExt1()!=null&&!czjvoteorder.getExt1().equals("")){
			map.put("ext1", czjvoteorder.getExt1());
		}
		if(czjvoteorder.getExt2()!=null&&!czjvoteorder.getExt2().equals("")){
			map.put("ext2", czjvoteorder.getExt2());
		}
		if(czjvoteorder.getExt3()!=null&&!czjvoteorder.getExt3().equals("")){
			map.put("ext3", czjvoteorder.getExt3());
		}
		if(czjvoteorder.getExt4()!=null&&!czjvoteorder.getExt4().equals("")){
			map.put("ext4", czjvoteorder.getExt4());
		}
		if(czjvoteorder.getExt5()!=null&&!czjvoteorder.getExt5().equals("")){
			map.put("ext5", czjvoteorder.getExt5());
		}
		if(czjvoteorder.getExt6()!=null&&!czjvoteorder.getExt6().equals("")){
			map.put("ext6", czjvoteorder.getExt6());
		}      
		return map;
	}
   
	/**
	 * 设置页面所需的数据字典
	 * @param model
	 */
	private void setDict(ModelMap model){
		
	}

	//删除更新的图片
	 public void deleteFile(String jgpName){	 
		 File f = new File(jgpName); // 输入要删除的文件位置
		 if(f.exists()){
			 f.delete();
		 }
		
	 }

   
      
	@Resource
	private CzjvoteorderService czjvoteorderService;


}